from presenter import basepresenter
from domain import article
from config import sitesettings
import datetime

class EditArticlePresenter(basepresenter.BasePresenter):

    def respondToGet(self):
        # get the article key
        if (self.request.get('key')):
            editarticle = self.articletask.getByKey(self.request.get('key'))
            self.template_values['article'] = editarticle
        else:
            editarticle = None
            settings = sitesettings.SiteSettings()
            self.template_values['defaultimage'] = settings.defaultarticleimage

        # set up the page title
        page_title = self.sitetitle + ' - Add / Edit Article'
        self.template_values['page_title'] = page_title

        #get the view to draw the page
        self.view.showGetResponse(self.template_values)

    def respondToPost(self):
        if (self.request.get('action') == "Delete"):
            oldarticle = self.articletask.getByKey(self.request.get('articlekey'))
            self.articletask.delete(oldarticle)
        else:
            # populate an article object from the request
            newarticle = article.Article()
            if (self.request.get('articlekey')):
                newarticle = self.articletask.getByKey(self.request.get('articlekey'))
            if (self.request.get('date')):
                newarticle.date = datetime.datetime.strptime(self.request.get('date'), "%Y-%m-%d")
            if self.currentuser:
                newarticle.author = self.currentuser
                newarticle.authornickname = self.currentuserprofile.nickname
            newarticle.title = self.request.get('title')
            newarticle.content = self.request.get('content')
            newarticle.summary = self.request.get('summary')
            newarticle.categories = self.request.get('categories', allow_multiple=True)
            newarticle.type = self.request.get('type')
            if (self.request.get('published')):
                newarticle.published = True
            else:
                newarticle.published = False
            if (self.request.get('mainfeature')):
                newarticle.mainfeature = True
            else:
                newarticle.mainfeature = False
            imageurl = self.request.get('imagelink')
            if (imageurl):
                newarticle.imagelink = self.request.get('imagelink')
            # create the task and save the article
            self.articletask.save(newarticle)

        #get the view to draw the page
        self.view.showPostResponse(self.template_values)